#include "mainworkthread.h"
#include <QDebug>

MainWorkThread::MainWorkThread(QObject *parent)
    : QThread(parent)
{
    miniCap = MiniCap::getInstance();
    miniTouch = MiniTouch::getInstance();
}

QMutex MainWorkThread::mutex;
QAtomicPointer<MainWorkThread> MainWorkThread::instance = 0;

MainWorkThread* MainWorkThread::getInstance()
{
#ifndef Q_ATOMIC_POINTER_TEST_AND_SET_IS_ALWAYS_NATIVE
    if(!QAtomicPointer<MiniCap>::isTestAndSetNative())
        qDebug("Error: TestAndSetNative not supported!");
#endif

    if(instance.testAndSetOrdered(0, 0))
    {
        QMutexLocker locker(&mutex);
        instance.testAndSetOrdered(0, new MainWorkThread);
    }
    return instance;
}

bool MainWorkThread::startMini(int mode){
    if(isFinished() && !isRunning()) {
        return false;
    }
    workMode = mode;
    start();
}

void MainWorkThread::run()
{
    QMutexLocker locker(&miniMutex);
    int ret;
    qDebug() << ((MODE_CAPTURE == (workMode & MODE_CAPTURE)) ? true : false);
    qDebug() << ((capStatus == STATUS_DISCONNECT)? true : false);
    if((MODE_CAPTURE == (workMode & MODE_CAPTURE)) && (capStatus == STATUS_DISCONNECT)) {
        capStatus = STATUS_CONNECTING;
        emit statusChangeSignal(MODE_CAPTURE, capStatus, touchStatus, 1);
        ret = miniCap->prepare();
        if(ret < 0){
            capStatus = STATUS_DISCONNECT;
        } else {
            ret = miniCap->startServer();
            capStatus = STATUS_CONNECTED;
        }
        emit statusChangeSignal(MODE_CAPTURE, capStatus, touchStatus, ret);
    }
    if ((MODE_TOUCH == (workMode & MODE_TOUCH))  && (touchStatus == STATUS_DISCONNECT)) {
        touchStatus = STATUS_CONNECTING;
        emit statusChangeSignal(MODE_CAPTURE, capStatus, touchStatus, 1);
        ret = miniTouch->prepare();
        if(ret < 0){
            touchStatus = STATUS_DISCONNECT;
        } else {
            touchStatus = STATUS_CONNECTED;
        }
        emit statusChangeSignal(MODE_CAPTURE, capStatus, touchStatus, ret);
    }
}

